<HEAD> <TITLE> foreach </TITLE> </HEAD> <BODY BACKGROUND="http://www.imaginary.com/LPMud/Graphics/RecycledPaper.jpg" TEXT=#000000 ALINK=#FFFF00 VLINK=#550000 LINK=#000099> <center> <H1> foreach </H1> </center>
<p>
foreach() loops can be used to iterate over the elements of an <A HREF=http://www.imaginary.com/~beek/mudos/lpc/array.html>  array </A> or
<A HREF=http://www.imaginary.com/~beek/mudos/lpc/mapping.html>  mapping </A>.  The <A HREF=http://www.imaginary.com/~beek/mudos/lpc/array.html>  array </A> form is:
<p>
<pre>
foreach (&#60;var&#62; in &#60;expr&#62;) {
    ...
}
</pre>
<p>
Where &#60;expr&#62; is any expression that returns an array.  For example,
<p>
<pre>
int x;
foreach (x in ({ 1, 2, 3, 4 })) {
    printf("%i ", x);
}
</pre>
<p>
is exactly the same as doing:
<p>
<pre>
int x, i, n;
int *y = ({ 1, 2, 3, 4 })
n = sizeof(y);
for (i = 0; i < n; i++) {
    x = y[i];
    printf("%i ", x);
}
</pre>
<p>
Note that &#60;expr&#62; is only evaluated once, at the start of the loop.  The
usual loop commands, like <A HREF=http://www.imaginary.com/~beek/mudos/lpc/break.html>  break </A> and <A HREF=http://www.imaginary.com/~beek/mudos/lpc/continue.html>  continue </A>, work within foreach loops
as well.
<p>
The second form is used to iterate over a <A HREF=http://www.imaginary.com/~beek/mudos/lpc/mapping.html>  mapping </A>:
<p>
<pre>
foreach (&#60;var&#62;, &#60;var&#62; in &#60;expr&#62;) {
    ...
}
</pre>
<p>
Each time through the loop, the first var is set to a key from the <A HREF=http://www.imaginary.com/~beek/mudos/lpc/mapping.html>  mapping </A>,
and the second is set to the corresponding value, so:
<p>
<pre>
int x, y;
foreach (x, y in ([ 1 : 2, 3 : 4, 5 : 6 ]) ) {
    printf("%i : %i\n", x, y);
}
</pre>
<p>
is the same as the considerably more complex:
<p>
<pre>
int x, y;
mapping m = ([ 1 : 2, 3 : 4, 5 : 6 ]);
int *k = keys(m);
int n = sizeof(k);
for (int i = 0; i < n; i++) {
    x = k[i];
    y = m[x];
    printf("%i : %i\n", x, y);
}    
</pre>
<p>
See also the summary of <A HREF=http://www.imaginary.com/~beek/mudos/lpc/loops.html>  loops </A>.
<p>
<HR> <ADDRESS> <A HREF=http://wagner.princeton.edu/~tim>  Tim Hollebeek </A> <p> <A HREF="http://www.imaginary.com/~beek/">  Beek </A>@ZorkMUD, Lima Bean, IdeaExchange, TMI-2, and elsewhere </ADDRESS>
